<template>
  <transition name="slide">
  <div class="xin-widget-citys animated" v-if="isShow">
    <div class="xin-widget-citys-content">
      <div class="xin-widget-citys-header bdb">
        <div class="xin-widget-citys-iptbox">
          <input type="text" placeholder="城市中文名或拼音" v-model="input">
        </div>
        <a href="javascript:void(0)" @click="hide">取消</a>
      </div>
      <div class="xin-widget-citys-local bdb">当前城市：{{localCity.cityName || "无法定位当前城市"}}</div>
      <div class="xin-widget-citys-list" v-if="input == ''">
        <dl>
          <template v-for="(item, index) in letterList">
            <template v-if="index == 'star'">
              <dt><em class="star-big"></em>热门城市</dt>
            </template>
            <template v-else>
              <dt v-if="isNaN(index)">{{index}}</dt>
            </template>
            <template v-for="(item2, key) in item">
              <dd @click="_chooseOne(item2)">{{item2.cityName}}</dd>
            </template>
          </template>
        </dl>
      </div>
      <div class="xin-widget-citys-searchlist" v-if="input !== ''">
        <ul v-if="searchList.length!==0">
          <li class="bdb" v-for="item in searchList" @click="_chooseOne(item)">{{item.cityName}}</li>
        </ul>
        <div v-else class="nomatch">没有匹配城市</div>
      </div>
    </div>
    <div class="xin-widget-citys-letnav" v-if="isShow && input == '' && !simple" @touchmove="_touchLetters">
      <ol>
        <template v-for="(item, index) in letterList">
          <li v-if="isNaN(index) && index=='star'" @click="_chooseLetter" data-type="starCity"><em class='star-small' data-type="starCity"></em></li>
          <li v-else @click="_chooseLetter" data-type="letter">{{index}}</li>
        </template>
      </ol>
    </div>
  </div>
  </transition>
</template>

<script>
export default {
  props: {
    isShow: {
      type: Boolean,
      default: false,
      required: false
    },
    simple: {
      type: Boolean,
      default: false
    },
    localCity: {
      type: Object
    },
    starCity: {
      type: Array
    },
    cityData: {
      type: Array
    },
    onChoose: {
      type: Function
    },
    initCity: {
      type: Function,
      default: null
    },
    close: {
      type: Function
    }
  },
  data: function() {
    return {
      input: '',
      list: '',
      targetLetter: '',
      searchList: [], // 搜索结果
      hotList: [],
      letterList: [],
      result: '',
      defaultTrigger: true
    }
  },
  watch: {
    cityData: function() {
      if (this.cityData && this.cityData.length > 0) {
        this._formatCityList(this.cityData)
      }
    },
    input: function() {
      this._search()
    },
    targetLetter: function() {
      this._scrollView()
    }
  },
  activate: function(done) {
    var _this = this

    done()
    if (_this.cityData && _this.cityData.length > 0) {
      _this._formatCityList(_this.cityData)
    }
  },
  methods: {
    show: function() {
      // this.isShow = true
    },
    hide: function() {
      // this.isShow = false
      this.input = ''
      this.searchList = []
      this.close && this.close()
    },
    _chooseDefault: function() {
      let _this = this
      let arr = this.list.filter(function(item) {
        return _this.localCity.cityId === item.cityId
      })
      if (arr.length > 0) {
        _this._chooseOne(arr[0])
      } else {
        _this._chooseOne(this.list[0])
      }
    },
    /**
     * 点击字母
     */
    _chooseLetter: function(e) {
      let symbol = e.target.getAttribute('data-type')

      if (symbol === 'starCity') {
        this.targetLetter = '热门城市'
      } else {
        this.targetLetter = e.target.innerText
      }
    },
    /**
     * slide letters list
     */
    _touchLetters: function(e) {
      e.preventDefault()

      let ol = document.querySelector('.xin-widget-citys-letnav ol')
      let liNum = document.querySelectorAll('.xin-widget-citys-letnav li').length
      let olHei = ol.clientHeight // ol height
      let liHei = Math.round(olHei / liNum) // li height
      let olTop = ol.offsetTop + ol.offsetParent.offsetTop
      let olBot = olTop + olHei
      let touchY = e.touches[0].pageY
      let $wrapper = document.querySelector('.xin-widget-citys')

      switch (e.type) {
        case 'touchstart':
          if (touchY < olTop) {
            // 回顶
            $wrapper.scrollTop = 0
          } else if (touchY > olBot) {
            // 到底
            $wrapper.scrollTop = 10000
          }
          break
        case 'touchmove':
          if (touchY < olBot && touchY > olTop) {
            let olTouchY = touchY - olTop
            let targetIndex = Math.ceil(olTouchY / liHei)
            let target = document.querySelectorAll('.xin-widget-citys-letnav li')[targetIndex - 1]

            if (target.getAttribute('data-type') === 'starCity') {
              this.targetLetter = '热门城市'
            } else {
              this.targetLetter = target.innerText
            }
          } else if (touchY <= olTop) {
            // 回顶
            $wrapper.scrollTop = 0
          } else {
            // 到底
            $wrapper.scrollTop = 10000
          }
          break
      }
    },
    /**
     * 滚动可视区 - Triggered by '_chooseLetter'
     */
    _scrollView: function() {
      let dtList = document.querySelectorAll('.xin-widget-citys-list dt')
      let _this = this
      let _dtList = Array.prototype.slice.call(dtList)

      if (_dtList) {
        _dtList.forEach((value, index, array) => {
          if (value.innerText === _this.targetLetter) {
            let wrapper = document.querySelector('.xin-widget-citys')
            let scrollTop = document.querySelector('.xin-widget-citys-list').offsetTop + value.offsetTop

            wrapper.scrollTop = scrollTop

            // setTimeout(function() {
            //   // 解决ios下 元素滚动的bug  现象是触发scroll时会导致部分滚动元素消失到二次元
            //   wrapper.style.width = (100 + (Math.round(Math.random() * 1000)) / 1000) + '%'
            // }, 0)
            return false
          }
        })
      }
    },
    /**
     * search city
     */
    _search: function() {
      var reg = new RegExp(this.input === '' ? 'xxyy' : this.input, 'ig')

      var _arr = []
      for (var i in this.letterList) {
        for (var j = 0; j < this.letterList[i].length; j++) {
          if (reg.test(this.letterList[i][j]['cityName']) || reg.test(this.letterList[i][j]['cityFirstLetter']) || reg.test(this.letterList[i][j]['citySpell'])) {
            _arr.push(this.letterList[i][j])
          }
        }
      }
      this.searchList = _arr
    },
    /**
     * format data of city
     * @param  {[Array]} arr [cityList]
     */
    _formatCityList: function(arr) {
      var letterArr = {}
      if (this.simple) {
        for (var i = 0; i < arr.length; i++) {
          letterArr[i] = []
          letterArr[i].push(arr[i])
        }
      } else {
        // 添加热门城市
        if (this.starCity && this.starCity.length > 0) {
          let _starCity = this.starCity

          _starCity.forEach((value, index, array) => {
            if (!('star' in letterArr)) {
              letterArr['star'] = []
              letterArr['star'].unshift(value)
            } else {
              letterArr['star'].unshift(value)
            }
          })
        }
        for (let i = 0; i < arr.length; i++) {
          if (!(arr[i]['cityFirstLetter'] in letterArr)) {
            letterArr[arr[i]['cityFirstLetter']] = []
            letterArr[arr[i]['cityFirstLetter']].push(arr[i])
          } else {
            letterArr[arr[i]['cityFirstLetter']].push(arr[i])
          }
        }
      }
      this.letterList = letterArr
    },
    _chooseOne: function(obj) {
      this.onChoose && this.onChoose(JSON.parse(JSON.stringify(obj)))
      // this.hide()
    }
  }
}
</script>
<style lang="sass" scoped>
@import "~@/assets/styles/base/city"
</style>
